package top.porchwood.jweb.mcsm.controller;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;

@Controller
public class ClientLoggerController {
    /**
     * 网络中的发送日志设备列表
     */
    private static final HashSet<String> client = new HashSet<>();
    /**
     * 发送日志的设备的日志缓冲区
     */
    private static final HashMap<String, StringBuilder> clientLog = new HashMap<>();
    /**
     * 发送和接收日志的设备映射表
     */
    private static final HashMap<String, String> clientMappingTable = new HashMap<>();

    @PostMapping("logger/login")
    private void onClientLogin(HttpServletRequest request, HttpServletResponse response) throws IOException{
        HttpSession session = request.getSession(true);

    }

    @PostMapping("logger/upload")
    private void onClientPostLogger(Principal principal, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        if (principal == null) {
            response.sendError(403, """
                    {"message": "你没有登录！"}
                    """);
            return;
        }
        String name = principal.getName();
        client.add(principal.getName());
        ArrayList<Character> characters = new ArrayList<>();
        characters.toArray(Character[]::new);
        InputStream stream = request.getInputStream();
        InputStreamReader isr = new InputStreamReader(stream);
        int length;
        char[] chars = new char[1024];
        while ((length = isr.read(chars)) > -1)
            characters.addAll(Arrays.asList(ArrayUtils.toObject(Arrays.copyOfRange(chars, 0, length))));
        response.setStatus(200);
        Writer writer= response.getWriter();
        writer.write("""
                {"message":"接收成功"}
                """);
        writer.close();
        if(!clientLog.containsKey(name)) clientLog.put(name, new StringBuilder());
        StringBuilder sb = clientLog.get(name);
        sb.append(ArrayUtils.toPrimitive(characters.toArray(Character[]::new)));
        if(sb.length() > 32768) sb.delete(0, sb.length() - 32768);
    }
    @GetMapping("logger/download")
    private void onClientGetLogger(Principal principal, HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.setCharacterEncoding("UTF-8");
        if (principal == null) {
            response.sendError(403, """
                    {"message": "你没有登录！"}
                    """);
            return;
        }
    }
}
